package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdminLoginMapper;
import com.heima.admin.service.AdminLoginService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminLoginServiceImpl extends ServiceImpl<AdminLoginMapper, AdUser> implements AdminLoginService {
    @Autowired
    private AdminLoginMapper adminLoginMapper;

    /**
     * 后台管理员登录功能
     * @param adUserDto
     * @return
     */
    @Override
    public ResponseResult login(AdUserDto adUserDto) {
        //1.校验参数
        if (adUserDto == null || StringUtils.isEmpty(adUserDto.getName())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //2.判断密码是否正确
        //2.1查询用户详情：获取盐和用户的加密密码
        LambdaQueryWrapper<AdUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdUser::getName, adUserDto.getName());
        AdUser adUser = adminLoginMapper.selectOne(queryWrapper);
        if (adUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        String salt = adUser.getSalt();
        String password = adUser.getPassword();
        //2.2获取用户输入的密码，得到进行加密
        String password1 = adUserDto.getPassword();
        String pwd = DigestUtils.md5DigestAsHex((password1 + salt).getBytes());
        //2.3比对
        if (!pwd.equals(password)){
            //密码错误
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        //3.生成token
        String token = AppJwtUtil.getToken(Long.valueOf(adUser.getId()));
        //封装数据
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        adUser.setSalt("");
        adUser.setPassword("");
        map.put("user",adUser);
        //4.返回结果
        return ResponseResult.okResult(map);
    }
}
